{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "5.4. 池化层.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/chongzicbo/Dive-into-Deep-Learning-tf.keras/blob/master/5.4.%20%E6%B1%A0%E5%8C%96%E5%B1%82.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZVSJ1ZUZqjcG",
        "colab_type": "text"
      },
      "source": [
        "##5.4. 池化层\n",
        "回忆一下，在“二维卷积层”一节里介绍的图像物体边缘检测应用中，我们构造卷积核从而精确地找到了像素变化的位置。设任意二维数组$X$的$i$行$j$列的元素为$X[i, j]$。如果我们构造的卷积核输出$Y[i, j]=1$，那么说明输入中$X[i, j]$和X$[i, j+1]$数值不一样。这可能意味着物体边缘通过这两个元素之间。但实际图像里，我们感兴趣的物体不会总出现在固定位置：即使我们连续拍摄同一个物体也极有可能出现像素位置上的偏移。这会导致同一个边缘对应的输出可能出现在卷积输出$Y$中的不同位置，进而对后面的模式识别造成不便。\n",
        "\n",
        "在本节中我们介绍池化（pooling）层，它的提出是为了缓解卷积层对位置的过度敏感性。\n",
        "\n",
        "###5.4.1. 二维最大池化层和平均池化层\n",
        "同卷积层一样，池化层每次对输入数据的一个固定形状窗口（又称池化窗口）中的元素计算输出。不同于卷积层里计算输入和核的互相关性，池化层直接计算池化窗口内元素的最大值或者平均值。该运算也分别叫做最大池化或平均池化。在二维最大池化中，池化窗口从输入数组的最左上方开始，按从左往右、从上往下的顺序，依次在输入数组上滑动。当池化窗口滑动到某一位置时，窗口中的输入子数组的最大值即输出数组中相应位置的元素。\n",
        "<center><img src=\"https://zh.gluon.ai/_images/pooling.svg\"></img></center>\n",
        "<center>图 5.6 池化窗口形状为 2×2 的最大池化</center>\n",
        "\n",
        "图5.6展示了池化窗口形状为 $2 \\times 2$ 的最大池化，阴影部分为第一个输出元素及其计算所使用的输入元素。输出数组的高和宽分别为2，其中的4个元素由取最大值运算 max 得出：\n",
        "$$\n",
        "\\begin{split}\\max(0,1,3,4)=4,\\\\\n",
        "\\max(1,2,4,5)=5,\\\\\n",
        "\\max(3,4,6,7)=7,\\\\\n",
        "\\max(4,5,7,8)=8.\\\\\\end{split}\n",
        "$$\n",
        "二维平均池化的工作原理与二维最大池化类似，但将最大运算符替换成平均运算符。池化窗口形状为 $p \\times q$ 的池化层称为 $p \\times q$ 池化层，其中的池化运算叫作 $p \\times q$ 池化。\n",
        "\n",
        "让我们再次回到本节开始提到的物体边缘检测的例子。现在我们将卷积层的输出作为 $2 \\times 2$ 最大池化的输入。设该卷积层输入是$X$、池化层输出为$Y$。无论是$X[i, j]$和$X[i, j+1]$值不同，还是$X[i, j+1]$和X$[i, j+2]$不同，池化层输出均有$Y[i, j]=1$。也就是说，使用 $2 \\times 2$ 最大池化层时，只要卷积层识别的模式在高和宽上移动不超过一个元素，我们依然可以将它检测出来。\n",
        "\n",
        "下面把池化层的前向计算实现在pool2d函数里。它跟“二维卷积层”一节里corr2d函数非常类似，唯一的区别在计算输出Y上。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HjNb_htD-UQx",
        "colab_type": "code",
        "outputId": "71bdf64f-a25a-4f29-eec9-cdf7f114a6e7",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 64
        }
      },
      "source": [
        " import tensorflow as tf\n",
        " from tensorflow import keras"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/html": [
              "<p style=\"color: red;\">\n",
              "The default version of TensorFlow in Colab will soon switch to TensorFlow 2.x.<br>\n",
              "We recommend you <a href=\"https://www.tensorflow.org/guide/migrate\" target=\"_blank\">upgrade</a> now \n",
              "or ensure your notebook will continue to use TensorFlow 1.x via the <code>%tensorflow_version 1.x</code> magic:\n",
              "<a href=\"https://colab.research.google.com/notebooks/tensorflow_version.ipynb\" target=\"_blank\">more info</a>.</p>\n"
            ],
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ]
          },
          "metadata": {
            "tags": []
          }
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kR-v3etM-fnF",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "tf.enable_eager_execution()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nmsBe1gx-h9t",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def pool2d(X,pool_size,mode='max'):\n",
        "  p_h,p_w=pool_size\n",
        "  Y=tf.Variable(tf.zeros((X.numpy().shape[0]-p_h+1,X.numpy().shape[1]-p_w+1)))\n",
        "  for i in range(Y.numpy().shape[0]):\n",
        "    for j in range(Y.numpy().shape[1]):\n",
        "      if mode=='max':\n",
        "        tf.assign(Y[i,j],tf.reduce_max(X[i:i+p_h,j:j+p_w]))\n",
        "      elif mode=='avg':\n",
        "        tf.assign(Y[i,j],tf.reduce_mean(X[i:i+p_h,j:j+p_w]))\n",
        "  return Y"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lD1TibntsB2C",
        "colab_type": "text"
      },
      "source": [
        "我们可以构造图5.6中的输入数组X来验证二维最大池化层的输出。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gdTmYtLq_d7k",
        "colab_type": "code",
        "outputId": "30bd37ba-dd57-45d6-ae0c-ea28b482588f",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 71
        }
      },
      "source": [
        "X=tf.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8]],dtype=tf.float32)\n",
        "pool2d(X,(2,2))"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=\n",
              "array([[4., 5.],\n",
              "       [7., 8.]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A4udmnkosFWS",
        "colab_type": "text"
      },
      "source": [
        "同时我们实验一下平均池化层。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "c4fThoiL_mGl",
        "colab_type": "code",
        "outputId": "2d842716-6a4d-41cc-c38e-e0991b52c102",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 71
        }
      },
      "source": [
        "pool2d(X,(2,2),'avg')"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=\n",
              "array([[2., 3.],\n",
              "       [5., 6.]], dtype=float32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6Xteq7lPsLb7",
        "colab_type": "text"
      },
      "source": [
        "###5.4.2. 填充和步幅\n",
        "同卷积层一样，池化层也可以在输入的高和宽两侧的填充并调整窗口的移动步幅来改变输出形状。池化层填充和步幅与卷积层填充和步幅的工作机制一样。我们将通过layers模块里的二维最大池化层MaxPool2D来演示池化层填充和步幅的工作机制。我们先构造一个形状为(1, 1, 4, 4)的输入数据，前两个维度分别是批量和通道。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Xe9fb8yoBAyb",
        "colab_type": "code",
        "outputId": "a3e3b5df-282a-49b7-cedd-3a5cefcb364f",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 377
        }
      },
      "source": [
        "X=tf.reshape(tf.range(16),shape=(1,4,4,1)) #[batch，height,width,channel]]\n",
        "X"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: id=129, shape=(1, 4, 4, 1), dtype=int32, numpy=\n",
              "array([[[[ 0],\n",
              "         [ 1],\n",
              "         [ 2],\n",
              "         [ 3]],\n",
              "\n",
              "        [[ 4],\n",
              "         [ 5],\n",
              "         [ 6],\n",
              "         [ 7]],\n",
              "\n",
              "        [[ 8],\n",
              "         [ 9],\n",
              "         [10],\n",
              "         [11]],\n",
              "\n",
              "        [[12],\n",
              "         [13],\n",
              "         [14],\n",
              "         [15]]]], dtype=int32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZATvNA14shdY",
        "colab_type": "text"
      },
      "source": [
        "默认情况下，MaxPool2D实例里步幅和池化窗口形状相同。下面使用形状为(3, 3)的池化窗口，默认获得形状为(3, 3)的步幅。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5w1hPJzcBNpg",
        "colab_type": "code",
        "outputId": "c71c5c8d-8523-43dd-e44c-b8a3cfdfaef6",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        }
      },
      "source": [
        "pool2d=keras.layers.MaxPool2D(pool_size=(3,3))\n",
        "pool2d(X).numpy()"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([[[[10]]]], dtype=int32)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "VSCKa2jyBald",
        "colab_type": "code",
        "outputId": "4476613c-3767-4f62-d1db-a96077315ae3",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 107
        }
      },
      "source": [
        "pool2d=keras.layers.MaxPool2D(2,strides=2)\n",
        "pool2d(X).numpy()"
      ],
      "execution_count": 0,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([[[[ 5],\n",
              "         [ 7]],\n",
              "\n",
              "        [[13],\n",
              "         [15]]]], dtype=int32)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 40
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bbP8xgx3snAF",
        "colab_type": "text"
      },
      "source": [
        "我们可以手动指定步幅和填充。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "E3yMD9rMDRpY",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "pool2d=keras.layers.MaxPool2D(pool_size=(2,3),padding='same',strides=(2,3))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "UuE3qwXGEr6l",
        "colab_type": "code",
        "outputId": "eaeb0a9b-6024-402a-8cbc-3d2db543a726",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 125
        }
      },
      "source": [
        "pool2d(X)"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: id=131, shape=(1, 2, 2, 1), dtype=int32, numpy=\n",
              "array([[[[ 5],\n",
              "         [ 7]],\n",
              "\n",
              "        [[13],\n",
              "         [15]]]], dtype=int32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yrMHvCBTswVj",
        "colab_type": "text"
      },
      "source": [
        "###5.4.3. 多通道\n",
        "在处理多通道输入数据时，池化层对每个输入通道分别池化，而不是像卷积层那样将各通道的输入按通道相加。这意味着池化层的输出通道数与输入通道数相等。下面将数组$X$和$X+1$在通道维上连结来构造通道数为2的输入。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "93_3RMBnEte_",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 377
        },
        "outputId": "b0b09ef0-10dc-4d9d-db21-1b956a3fad66"
      },
      "source": [
        "X=tf.concat((X,X+1),axis=-1)\n",
        "X"
      ],
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: id=135, shape=(1, 4, 4, 2), dtype=int32, numpy=\n",
              "array([[[[ 0,  1],\n",
              "         [ 1,  2],\n",
              "         [ 2,  3],\n",
              "         [ 3,  4]],\n",
              "\n",
              "        [[ 4,  5],\n",
              "         [ 5,  6],\n",
              "         [ 6,  7],\n",
              "         [ 7,  8]],\n",
              "\n",
              "        [[ 8,  9],\n",
              "         [ 9, 10],\n",
              "         [10, 11],\n",
              "         [11, 12]],\n",
              "\n",
              "        [[12, 13],\n",
              "         [13, 14],\n",
              "         [14, 15],\n",
              "         [15, 16]]]], dtype=int32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 10
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pYlfWIK8s87M",
        "colab_type": "text"
      },
      "source": [
        "池化后，我们发现输出通道数仍然是2。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4H78ptmfFAWX",
        "colab_type": "code",
        "outputId": "ada8dc97-4f5a-4006-cd9d-29c50f093603",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 125
        }
      },
      "source": [
        "pool2d=keras.layers.MaxPool2D(3,padding='same',strides=2)\n",
        "pool2d(X)"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: id=137, shape=(1, 2, 2, 2), dtype=int32, numpy=\n",
              "array([[[[10, 11],\n",
              "         [11, 12]],\n",
              "\n",
              "        [[14, 15],\n",
              "         [15, 16]]]], dtype=int32)>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 12
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "q1w63ggVFnbf",
        "colab_type": "text"
      },
      "source": [
        "###5.4.4. 小结\n",
        "* 最大池化和平均池化分别取池化窗口中输入元素的最大值和平均值作为输出。\n",
        "* 池化层的一个主要作用是缓解卷积层对位置的过度敏感性。\n",
        "* 可以指定池化层的填充和步幅。\n",
        "* 池化层的输出通道数跟输入通道数相同。"
      ]
    }
  ]
}